package com.tiny.tinyweb.core.jsf;

import java.util.Map;

import javax.faces.context.FacesContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * 让Spring的Managed Bean支持JSF2的ViewScope的Scope配置类。
 *
 * @author wxiaobin
 */
public class ViewScope implements Scope {
    private final static Logger logger = LoggerFactory.getLogger(ViewScope.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public Object get(String name, ObjectFactory<?> objectFactory) {
        if (FacesContext.getCurrentInstance().getViewRoot() != null) {
            Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
            if (viewMap.containsKey(name)) {
                logger.trace("Getting view scope bean:" + name);
                return viewMap.get(name);
            } else {
                logger.trace("Creating view scope bean:" + name);
                Object object = objectFactory.getObject();
                viewMap.put(name, object);
                return object;
            }
        } else {
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object remove(String name) {
        if (FacesContext.getCurrentInstance().getViewRoot() != null) {
            logger.trace("Removing view scope bean:" + name);
            return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
        } else {
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void registerDestructionCallback(String name, Runnable callback) {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object resolveContextualObject(String key) {
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getConversationId() {
        return null;
    }
}
